package com.star.robot.controller;

import com.star.robot.constant.Constant;
import com.star.robot.dto.CityProjectRequestDto;
import com.star.robot.dto.CityProjectRequestDto;
import com.star.robot.dto.PageResultDto;
import com.star.robot.dto.ProjectReqDto;
import com.star.robot.dto.ResultDto;
import com.star.robot.dto.TeamMemberQueryDto;
import com.star.robot.entity.*;
import com.star.robot.enums.AdminTypeEnum;
import com.star.robot.enums.ProjectClassEnum;
import com.star.robot.enums.ProjectLevelEnum;
import com.star.robot.repository.DtAreaRepositoty;
import com.star.robot.repository.ProjectClassEnumRepository;
import com.star.robot.repository.ProjectClassRepository;
import com.star.robot.repository.ProjectRepository;
import com.star.robot.service.AdminService;
import com.star.robot.service.UserService;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiOperation;
import org.hibernate.transform.Transformers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.data.web.PageableDefault;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.servlet.http.HttpServletRequest;
import java.math.BigInteger;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 项目管理
 */
@RestController
@RequestMapping("/project")
public class ProjectController {


    @Autowired
    private ProjectRepository projectRepository;

    @Autowired
    private AdminService adminService;

    @Autowired
    private DtAreaRepositoty dtAreaRepositoty;

    @Autowired
    ProjectClassEnumRepository projectClassEnumRepository;

    @Autowired
    ProjectClassRepository projectClassRepository;

    @Autowired
    UserService userService ;
    @PersistenceContext //注入的是实体管理器,执行持久化操作
            EntityManager entityManager;

    @PostMapping(value = "/")
    public ResultDto add(@RequestBody Project project, HttpServletRequest httpServletRequest){
        if(project.getProjectLevelEnum() == null){
            Admin admin = adminService.getCurrentAdmin(httpServletRequest);
            if(admin != null){
                if(admin.getAdminTypeEnum() == AdminTypeEnum.PROVINCEADMIN){
                    project.setProjectLevelEnum(ProjectLevelEnum.PROVINCELEVEL);
                }else if(admin.getAdminTypeEnum() == AdminTypeEnum.CITYADMIN){
                    project.setProjectLevelEnum(ProjectLevelEnum.CITYLEVEL);
                }else{
                    return ResultDto.builder().build();
                }
            }
        }
        projectRepository.save(project);
        return ResultDto.builder().build();
    }

    @GetMapping(value = "/isVisible")
    public ModelAndView isVisible(long id, boolean status, HttpServletRequest httpServletRequest){
        Project project = projectRepository.findLongById(id);
        project.setStatus(status);
        projectRepository.save(project);
        ModelAndView mav = new ModelAndView();
        mav.setViewName("/project/projectList");
        return mav;
    }
    @GetMapping(value = "/")
    public PageResultDto get( ProjectReqDto requestDto,HttpServletRequest request) {
        PageResultDto<Project> results = new PageResultDto<>();
        if (requestDto.getPage() != null && requestDto.getLimit() != null) {
            //后端框架分页从0开始 前端框架从1开始
            if (requestDto.getPage() >= 1) {
                requestDto.setPage(requestDto.getPage() - 1);
            }
            Pageable page = new PageRequest(requestDto.getPage(), requestDto.getLimit());
            Page pagedPro = projectRepository.findAll(new Specification<Project>() {
                @Override
                public Predicate toPredicate(Root<Project> root, CriteriaQuery<?> cq, CriteriaBuilder cb) {
                    List<Predicate> predicateList = new ArrayList<>();


//                    Long cityId = adminService.getCurrentAdminCityId(request);
//                    if(cityId != null){
//                        //所在地区
//                        Predicate cityCondition = cb.equal(root.get("city").get("id") ,cityId);
//                        predicateList.add(cityCondition);
//                    }

                    //修改项目
                    if (requestDto != null && requestDto.getId() != null) {
                        predicateList.add(cb.equal(root.get("id"), requestDto.getId()));
                    }


                    Predicate[] pre = new Predicate[predicateList.size()];
                    cq.where(predicateList.toArray(pre));
                    return cq.getRestriction();
                }
            }, page);

            results.setCount(pagedPro.getTotalElements());
            results.setData(pagedPro.getContent());
        }
        return results;
    }

    @GetMapping(value = "/list")
    public PageResultDto getList( ProjectReqDto requestDto,HttpServletRequest request) {
        PageResultDto result = new PageResultDto();
        int page = requestDto.getPage();
        int limit = requestDto.getLimit();
        StringBuffer sb = new StringBuffer("SELECT a.*,b.area_name FROM project a LEFT JOIN dt_area b ON a.city_id = b.id");
        StringBuffer sb1 = new StringBuffer("SELECT count(*) FROM project a LEFT JOIN dt_area b ON a.city_id = b.id");
        if(requestDto.getName() != null && !"".equals(requestDto.getName())){
            sb.append(" and b.name like %'" +requestDto.getName()+"'%" );
            sb1.append(" and b.name like %'" +requestDto.getName()+"'%" );
        }
        sb.append(" limit " +(page-1)*limit+","+limit);
//        Query query = entityManager.createNativeQuery(sb.toString(),Map.class);
        Query query = entityManager.createNativeQuery(sb.toString());
        query.unwrap(org.hibernate.SQLQuery.class)
                .setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
        List<Map<String,Object>> list = query.getResultList();
        Query query1 = entityManager.createNativeQuery(sb1.toString());
        Long count = ((BigInteger)query1.getSingleResult()).longValue();
        if(list.get(0).get("id") != null) {
            result.setData(list);
        }
        result.setCount(count);
        return result;
    }

    @GetMapping(value = "/queryProject")
    public ResultDto queryProject(){
        List<Map<String,Object>> projectList = projectRepository.queryProject();
        ResultDto resultDto = new ResultDto<>();
        resultDto.setData(projectList);
        resultDto.setCode(0);
        resultDto.setMessage("查询成功");
        resultDto.setSuccess(true);
        return resultDto;
    }

    @PostMapping(value = "/addCityProject")
    public ResultDto addCityProject(@RequestBody CityProjectRequestDto cityProjectRequestDto, HttpServletRequest httpServletRequest){
        Project project = projectRepository.findLongById(cityProjectRequestDto.getParentId());

        Project shiJiProject=new Project();


        if (cityProjectRequestDto.getBaoMingStartTime() != null) {
            shiJiProject.setBaoMingStartTime(cityProjectRequestDto.getBaoMingStartTime());
        }
        if (cityProjectRequestDto.getBaoMingEndTime() != null) {
            shiJiProject.setBaoMingEndTime(cityProjectRequestDto.getBaoMingEndTime());
        }
        if (cityProjectRequestDto.getProjectEndTime() != null) {
            shiJiProject.setProjectEndTime(cityProjectRequestDto.getProjectEndTime());
        }

        shiJiProject.setDescr(cityProjectRequestDto.getDescr());

        if (cityProjectRequestDto.getDescr() == null) {
            shiJiProject.setDescr(project.getDescr());
        }


        shiJiProject.setName(project.getName());
        shiJiProject.setParentid(cityProjectRequestDto.getParentId());
        shiJiProject.setProjectLevelEnum(ProjectLevelEnum.CITYLEVEL);
        shiJiProject.setStatus(cityProjectRequestDto.getStatus());
        shiJiProject.setTeamMemberCount(project.getTeamMemberCount());



        Admin admin=adminService.getCurrentAdmin(httpServletRequest);
        DtArea dtArea=dtAreaRepositoty.findByid(admin.getCityId());
        shiJiProject.setCity(dtArea);

        //因为下一步保存组别需要project的id所以先save
        projectRepository.save(shiJiProject);

        //jpa关联关系一对多， 不能在一的这方 保存多的一方，所以要用多的一方保存一的这方
        for (ProjectClassEnum projectClassEnum : cityProjectRequestDto.getProjectClassEnum()) {
            ProjectClass projectClass=new ProjectClass();
            ProjectClass exist = projectClassRepository.findByProjectClassEnumAndProject_Id(projectClassEnum , shiJiProject.getId());
            projectClass.setCode(projectClassEnum.getCode());
            projectClass.setName(projectClassEnum.getName());
            projectClass.setProjectClassEnum(projectClassEnum);
            projectClass.setProject(shiJiProject);

            //conflict with exists record , do nothing
            if(exist == null){
                projectClassRepository.save(projectClass);
            }
        }

        return ResultDto.builder().build();
    }

}
